﻿unit AgentRepFrm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  cxGridExportLink,
  dxRibbonForm,
  FIBQuery, pFIBCacheQueries,
  Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
  dxSkinsCore, dxSkinMcSkin, dxSkinOffice2010Black, dxSkinOffice2010Blue,
  dxSkinOffice2010Silver, dxSkinSeven, dxSkinsdxRibbonPainter,
  dxSkinsdxBarPainter, dxStatusBar, dxRibbonStatusBar, dxBar, cxClasses,
  dxRibbon, dxBarExtItems, cxPropertiesStore, cxStyles, dxSkinscxPCPainter,
  cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
  MemTableDataEh, MemTableEh, cxGridLevel, cxGridCustomView,
  cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxSplitter,
  ExtCtrls, dxsbar, dxSkinsdxNavBar2Painter, dxNavBar, dxNavBarCollns,
  dxNavBarBase, dxNavBarGroupItems, cxContainer, cxTextEdit, cxMaskEdit,
  cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
  dxLayoutcxEditAdapters, dxLayoutControl, Menus, StdCtrls, cxButtons,
  cxSpinEdit, FIBDataSet, pFIBDataSet, dxLayoutLookAndFeels, cxProgressBar,
  JvDialogs, cxFilterControl, cxDBFilterControl;

type
  TAgentRepForm = class(Tdxcustomribbonform)
    RibbonTab: TdxRibbonTab;
    dxRibbon1: TdxRibbon;
    barmen1: TdxBarManager;
    Bar1: TdxBar;
    btn_agrep: TdxBarButton;
    stbar1: TdxRibbonStatusBar;
    dt1: TdxBarDateCombo;
    prop1: TcxPropertiesStore;
    v1: TcxGridDBTableView;
    l1: TcxGridLevel;
    grd1: TcxGrid;
    tbl: TMemTableEh;
    ds1: TDataSource;
    clAcCode: TcxGridDBColumn;
    clSum3: TcxGridDBColumn;
    clSum4: TcxGridDBColumn;
    clSum5: TcxGridDBColumn;
    clSum6: TcxGridDBColumn;
    clSum7: TcxGridDBColumn;
    clSum8: TcxGridDBColumn;
    clSum9: TcxGridDBColumn;
    cbb1: TcxLookupComboBox;
    lcontr1Group_Root: TdxLayoutGroup;
    lcontr1: TdxLayoutControl;
    lGrp: TdxLayoutGroup;
    litem: TdxLayoutItem;
    lcontr1Item1: TdxLayoutItem;
    btn1: TcxButton;
    intedt1: TcxSpinEdit;
    lcontr1Item2: TdxLayoutItem;
    lcontr1Item3: TdxLayoutItem;
    cbb2: TcxComboBox;
    lGrplcontr1Group3: TdxLayoutGroup;
    lGrplcontr1Group1: TdxLayoutGroup;
    sep: TdxLayoutSeparatorItem;
    split1: TcxSplitter;
    DS2: TpFIBDataSet;
    ds3: TDataSource;
    LaFls1: TdxLayoutLookAndFeelList;
    dxlytcxlkndfl1: TdxLayoutCxLookAndFeel;
    lbl: TdxLayoutLabeledItem;
    cpanel: TdxStatusBarContainerControl;
    prbr1: TcxProgressBar;
    stile: TcxStyleRepository;
    styl1: TcxStyle;
    btn2: TcxButton;
    lItemlcontr1Item5: TdxLayoutItem;
    dlg1: TJvSaveDialog;
    sep1: TdxLayoutSeparatorItem;
    clv1SumAll: TcxGridDBColumn;
    clv1AIndex: TcxGridDBColumn;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure FormDeactivate(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure dt1Change(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure btn_agrepClick(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure lcontr1Click(Sender: TObject);
  private
    { Private declarations }
    Schet,Sum3,Sum4,Sum5,Sum6,Sum8,Kontr :TStringList;
    AIndex :TStringList;
    StartTime :TTime;
    reestr,
    BeginDate :string; //начальная дата передачи счета в работу
    function GetYM(M,Y: integer): string;
    function GetListYm(YM :string) :string;
    function GetSrv(kontr :string) :string;
    procedure CreateTable;
    procedure GetAcCode(reestr :Integer);
    procedure GetSumFromStat;
    procedure ExData(s :string);
    procedure AddData;
    procedure GetSumOpl(s :string);
    procedure Outstanding(s :string);
    procedure GetDolg(ls :TStringList);
{------------------------------------------------------------------------------}
    procedure GetBeforePeriodSumm(s :string);
    function GetEndPeriod(ym :string) :TDateTime;
    function GetBeginPeriod (ym: string) :TDateTime;

  public
    { Public declarations }
  end;

var
  AgentRepForm: TAgentRepForm;

implementation

uses cmUtils, MainFrm, DModule;

{$R *.dfm}

function TAgentRepForm.GetYM(M,Y: integer): string;
begin
 Result:=IntToStr(M);
 if Length(Result)=1 then Result:='0'+Result;
 Result:=Copy(IntToStr(Y),3,2)+Result;
end;

procedure TAgentRepForm.lcontr1Click(Sender: TObject);
begin
 //ShowMessage(GetSrv('1-1'));
end;

procedure TAgentRepForm.dt1Change(Sender: TObject);
begin
 btn_agrep.Caption:='Сформировать за '+
  FormatDateTime('YY',dt1.Date)
  +FormatDateTime('MM', dt1.Date);
end;

procedure TAgentRepForm.FormActivate(Sender: TObject);
begin
 //MainForm.AgentBar.Visible:=true;
end;

procedure TAgentRepForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
 RemoveBtn(Name);
 MainForm.AgentBar.Visible:=false;
 Schet.Free;Sum4.Free;Sum5.Free;Sum3.Free;Sum6.free;Sum8.Free;Kontr.Free;
 AIndex.Free;
 Action:=caFree;
end;

procedure TAgentRepForm.FormCreate(Sender: TObject);
begin
 AddButton(self);
  prop1.StorageName:=ExtractFilePath(Application.ExeName)+'config\AgentRepForm';
  prop1.Active:=True;
  if FileExists(ExtractFilePath(Application.ExeName)+'config\AgentRepForm') then
  prop1.RestoreFrom;
  //MainForm.AgentBar.Visible:=True;
  CreateTable;
  DS2.CloseOpen(true);
  Schet:=TStringList.Create;
  Sum4:=TStringList.Create;
  Sum5:=TStringList.Create;
  Sum6:=TStringList.Create;
  Sum3:=TStringList.Create;
  Sum8:=TStringList.Create;
  Kontr:=TStringList.Create;
  AIndex:=TStringList.Create;
end;
{-------------------------------------------------------------------------------
GetAcCode | Получаем счета и суммы из реестра
-------------------------------------------------------------------------------}
procedure TAgentRepForm.GetAcCode(reestr :Integer);
var
  Q :TFIBQuery;
  ym :string;
begin
  ym:=GetYM(cbb2.ItemIndex+1,intedt1.Value);
  Q:=GetQueryForUse(dm1.trnRD,
           // 'Select AcCode,Summa from N_REESTRDATA where reestr=:reestr');
      'Select r.AcCode,r.Summa,sc.kontragent,r.AIndex from N_REESTRDATA r'+
      ' left outer join spr$schet sc on sc.code=r.accode'+
      ' where r.reestr=:reestr');
  Q.ParamByName('reestr').AsInteger:=reestr;
  Q.ExecQuery;
  if not tbl.IsEmpty then tbl.EmptyTable;
  Schet.Clear; Sum4.Clear; Sum5.Clear;Sum3.Clear; AIndex.Clear;

  prbr1.Properties.Text:='Получаем счета ...';
  while not Q.Eof do
  begin
    Application.ProcessMessages;
    Schet.Add(Q.FN('AcCode').AsString);
    Sum5.Values[Q.FN('AcCode').AsString]:=Q.FN('Summa').AsString;
    Kontr.Values[Q.FN('AcCode').AsString]:=Q.FN('kontragent').AsString;
    AIndex.Values[Q.FN('AcCode').AsString]:=Q.FN('AIndex').AsString;
    Q.Next;
  end;
  prbr1.Properties.Min:=0;
  prbr1.Properties.Max:=Schet.Count*2;
  prbr1.Position:=0;
  GetSumFromStat;
  FreeQueryForUse(Q);
end;
{-------------------------------------------------------------------------------
GetSumFromStat | Получае суммы из N_ReestrStat
-------------------------------------------------------------------------------}
procedure TAgentRepForm.GetSumFromStat;
var
  i,n :Integer;
  pos :Double;
  s :string;
begin
  n:=0; S:='';
  for i:=0 to Schet.Count -1 do
   begin
     inc(n);
     if S<>'' then S:=S+',';
     S:=S+#39+Schet[i]+#39;
     if (n=1000) then
      begin
       ExData(S);
       //GetSumOpl(S);
       //Outstanding(S);
       GetBeforePeriodSumm(S);
       n:=0; S:='';
      end;
       //prbr1.Position:=Schet.Count;
       stbar1.Panels[0].Text:=IntToStr(i);
       Application.ProcessMessages;
       prbr1.Position:=i;
   end;
   if S<>'' then
   begin
    //GetSumOpl(S);
    ExData(S);
    //Outstanding(S);
    GetBeforePeriodSumm(S);
   end;
   GetDolg(Schet);
   AddData;
end;
{-------------------------------------------------------------------------------
GetSumOpl | Получаем суммы оплат
-------------------------------------------------------------------------------}
procedure TAgentRepForm.GetSumOpl(s :string);
var
  Q :TFIBQuery;
  ym :string;
begin
  ym:=GetYM(cbb2.ItemIndex+1,intedt1.Value);
   Q:=GetQueryForUse(dm1.trnRD,
  'select ns.acccode,ns.summa sum3 from n_reestrstat ns'+
  ' where ns.ym=:ym and ns.acccode in ('+s+')'+
  ' and ns.reestr=:reestr');
  Q.ParamByName('ym').AsString:=ym;
  Q.ParamByName('reestr').AsInteger:=StrToInt(reestr);
   Q.ExecQuery;
   while not Q.Eof do
   begin
     Sum3.Values[Q.FN('acccode').AsString]:=Q.FN('sum3').AsString;
     Application.ProcessMessages;
     Q.Next;
   end;
  FreeQueryForUse(Q);
end;

function TAgentRepForm.GetSrv(kontr :string) :string;
begin
  if (Kontr='1-1') or (Kontr='1-17') then
   Result:=#39+'40001154'+#39+','+#39+'4000113'+#39 else
   Result:=#39+'2548230148'+#39+','+#39+'2548137475'+#39;
end;

procedure TAgentRepForm.ExData(s :string);
var
  Q :TFIBQuery;
  ym,sql,srv :string;
  d1,d2 :TDate;
 procedure GetPeriod(ym: string);
 var
  m,nextm,y,nexty :string;
  d3:TDate;
 begin
  m:=Copy(ym,3,2);
  y:=Copy(ym,1,2);
  d1:=StrToDate('01.'+m+'.'+y);
  //d1:=StrToDate(BeginDate);
  if m='12'then
  begin
    nextm:='01';
    nexty:=IntToStr(StrToInt(y)+1);
  end else
  begin
    nextm:=IntToStr(StrToInt(m)+1);
    nexty:=y;
  end;
  d3:=StrToDate('01.'+nextm+'.'+nexty);
  d2:=d3-1;
 end;
begin
  ym:=GetYM(cbb2.ItemIndex+1,intedt1.Value);
  GetPeriod(ym);
  sql:='select acccode,Summa*-1 sum4,srv from SchetPrv WHERE Val_Date BETWEEN '+
  ' :d1 and :d2'+
  '  and acccode in('+s+
  ') and Prv_Type=1 order by acccode';
  {sql:=
  'select ns.acccode,ns.summa sum4 from n_reestrstat ns'+
  ' where ns.ym>=:ym and ns.ym<=:ym1 and ns.acccode in ('+s+')'+
  ' and ns.reestr=:reestr'; }
  Q:=GetQueryForUse(dm1.trnRD,sql);
  {Q.ParamByName('ym').AsString:=Copy(BeginDate,9,2)+Copy(BeginDate,4,2);
  Q.ParamByName('ym1').AsString:=ym; }
  //Q.ParamByName('reestr').AsInteger:=StrToInt(reestr);
  Q.ParamByName('d1').AsDate:=d1;
  Q.ParamByName('d2').AsDate:=d2;
   Q.ExecQuery;
   prbr1.Properties.Text:='Получаем суммы оплат ...';
   while not Q.Eof do
   begin
     if (Kontr.Values[Q.FN('acccode').AsString]='1-1') or
     (Kontr.Values[Q.FN('acccode').AsString]='1-17') then
     srv:=';4000115;4000113;' else
     Srv:=';2548230148;2548137475;';
     if (Pos(';'+Q.FN('Srv').AsString+';', Srv)>0) then
     Sum4.Values[Q.FN('acccode').AsString]:=FloatToStr
     (StrToFloatDef(Sum4.Values[Q.FN('acccode').AsString],0)+
      Q.FN('sum4').AsFloat);
     //stbar1.Panels[0].Text:=IntToStr(Sum5.Count);
     Application.ProcessMessages;
     Q.Next;
   end;
  FreeQueryForUse(Q);
end;
//получаем непогашенный остаток переданного долга на начало
{ TODO :
Во все запросы из n_reestrstat добавить в условие where реестр по которому работаем
 and reestr=:resstr }
procedure TAgentRepForm.Outstanding(s :string);
var
  Q :TFIBQuery;
  ym, beginYM, sql :string;
  SaldoBegin: Currency;
begin
  ym:=GetYM(cbb2.ItemIndex+1,intedt1.Value);
  //beginYM:=Copy(BeginDate,3,4)+Copy(BeginDate,6,7);
  Q:=GetQueryForUse(dm1.trnRD,
  'select ns.acccode,sum(ns.summa) sum6 from n_reestrstat ns'+
  ' where ns.ym <:ym and ns.ym>=:ym1 and ns.acccode in ('+s+')'+
  ' and ns.reestr=:reestr '+
  ' group by ns.acccode');
   Q.ParamByName('ym').AsString:=ym;
   Q.ParamByName('ym1').AsString:=Copy(BeginDate,9,2)+Copy(BeginDate,4,2);
   Q.ParamByName('reestr').AsInteger:=StrToInt(reestr);
   Q.ExecQuery;
   prbr1.Properties.Text:='Получаем непогашенный остаток переданного долга на начало ...';
   while not Q.Eof do
   begin
     Sum6.Values[Q.FN('acccode').AsString]:=Q.FN('sum6').AsString;
     //stbar1.Panels[0].Text:=IntToStr(Sum5.Count);
     Application.ProcessMessages;
     Q.Next;
   end;
  FreeQueryForUse(Q);
end;
{------------------------------------------------------------------------------
GetDolg:  Получаем задолженность на конец периода
_______________________________________________________________________________}
procedure TAgentRepForm.GetDolg(ls :TStringList);
var
  Q :TFIBQuery;
  d3 :TDate;
  ym :string;
  i :Integer;
 function GetPeriod(ym: string) :TDate;
 var
  m,nextm,y,nexty :string;
 begin
  m:=Copy(ym,3,2);
  y:=Copy(ym,1,2);
  if m='12'then
  begin
    nextm:='01';
    nexty:=IntToStr(StrToInt(y)+1);
  end else
  begin
    nextm:=IntToStr(StrToInt(m)+1);
    nexty:=y;
  end;
  d3:=StrToDate('01.'+nextm+'.'+nexty);
  Result:=d3;
 end;

begin
 ym:=GetYM(cbb2.ItemIndex+1,intedt1.Value);
 d3:=GetPeriod(ym);
 Q:=GetQueryForUse(dm1.trnRD,'SELECT SUMMA  from scansaldo(:ACCCODE,:d3,:srv)');
 for I := 0 to Ls.Count - 1 do
 begin
   Q.ParamByName('d3').AsDate:=d3;
      if (Kontr.Values[ls[i]]='1-1') or
     (Kontr.Values[ls[i]]='1-17') then
     Q.ParamByName('srv').AsString:=';4000115;4000113;' else
     Q.ParamByName('srv').AsString:=';2548230148;2548137475;';
   Q.ParamByName('ACCCODE').AsString:=ls[i];
   Q.Prepare;
   Q.ExecQuery;
   Sum8.Values[ls[i]]:=Q.FN('SUMMA').AsString;
   prbr1.Properties.Text:='Получаем задолженность на конец периода  '+
                                                                    intToSTr(i);
   Application.ProcessMessages;
 end;
 FreeQueryForUse(Q);
end;

procedure TAgentRepForm.AddData;
var
  i :Integer;
  pos :Double;
begin
  v1.DataController.DataSource:=nil;
  prbr1.Properties.Text:='Заполняем таблицу...';
  pos:=prbr1.Position;
  for I := 0 to Schet.Count - 1 do
  begin
    if ((StrToCurrDef(Sum5.Values[Schet[i]],0) -
                          StrToCurrDef(Sum6.Values[Schet[i]],0))>0)
     and ((StrToCurrDef(Sum4.Values[Schet[i]],0))>0)
    then
    begin
      tbl.Append;
       tbl.FieldByName('AcCode').AsString:=Schet[i];
    //Общая сумма оплат за период
       tbl.FieldByName('Sum4').AsCurrency:=
            StrToCurrDef(Sum4.Values[Schet[i]],0);
     //Сумма переданного долга
       tbl.FieldByName('Sum5').AsCurrency:=
            StrToCurrDef(Sum5.Values[Schet[i]],0);
      //Непогашенный остаток переданного долга на нач
       tbl.FieldByName('Sum6').AsCurrency:=
            StrToCurrDef(Sum5.Values[Schet[i]],0)-
            StrToCurrDef(Sum6.Values[Schet[i]],0);
      //Сумма оплаты
      if tbl.FieldByName('Sum4').AsCurrency >
                                         tbl.FieldByName('Sum6').AsCurrency then
      tbl.FieldByName('Sum3').AsCurrency:=tbl.FieldByName('Sum6').AsCurrency else
      tbl.FieldByName('Sum3').AsCurrency:=StrToCurrDef(Sum4.Values[Schet[i]],0);


       {if tbl.FieldByName('Sum5').AsCurrency<
                                        tbl.FieldByName('Sum4').AsCurrency then
       tbl.FieldByName('SumAll').AsCurrency:=tbl.FieldByName('Sum5').AsCurrency
       else
       tbl.FieldByName('SumAll').AsCurrency:=tbl.FieldByName('Sum4').AsCurrency;}

       tbl.FieldByName('Sum7').AsCurrency:=          //Непогашенный остаток
            tbl.FieldByName('Sum6').AsCurrency-      //переданного долга на кон.
            tbl.FieldByName('Sum3').AsCurrency;

       tbl.FieldByName('Sum8').AsCurrency:=          //Задолженность на конец периодам
            StrToCurrDef(Sum8.Values[Schet[i]],0);

       tbl.FieldByName('Sum9').AsCurrency:=          //Сумма для расчета вознаграждения 2%
            StrToCurrDef(Sum4.Values[Schet[i]],0)-
            tbl.FieldByName('Sum3').AsCurrency;
       tbl.FieldByName('AIndex').AsInteger:=
                                         StrToIntDef(AIndex.Values[Schet[i]],0);


      prbr1.Position:=pos+i;
      //stbar1.Panels[0].Text:=IntToStr(Schet.Count);
      Application.ProcessMessages;
      tbl.Post;
    end;
  end;
  v1.DataController.DataSource:=ds1;
  stbar1.Panels[1].Text:=TimeToStr(Time-StartTime);
  prbr1.Position:=0;
  prbr1.Properties.Text:='Формирование завершенно.';

end;

procedure TAgentRepForm.FormDeactivate(Sender: TObject);
begin
 MainForm.AgentBar.Visible:=false;
end;
{-------------------------------------------------------------------------------
CreateTable | Создаем таблицу в памяти
-------------------------------------------------------------------------------}
procedure TAgentRepForm.CreateTable;
begin
 with tbl.FieldDefs do
 begin
   Add('AcCode',ftString,32,True);
   Add('Sum3',ftCurrency);  //Сумма оплаты
   Add('Sum4',ftCurrency);  //Общая сумма оплат за период
   Add('Sum5',ftCurrency);  //Сумма переданного долга
   Add('Sum6',ftCurrency);  //Непогашенный остаток переданного долга на нач.
   Add('Sum7',ftCurrency);  //Непогашенный остаток переданного долга на кон.
   Add('Sum8',ftCurrency);  //Задолженность на конец периода
   Add('SumAll',ftCurrency);//Сумма оплат всего (непревышающая переданного долга)
   Add('Sum9',ftCurrency);  //Сумма для расчета вознаграждения 2%
   Add('SumOpl',ftCurrency); //Оплаты с момента передачи до начала отч. периода
   Add('AIndex',ftInteger);
 end;
  tbl.CreateDataSet;
  tbl.Open;
end;

procedure TAgentRepForm.btn1Click(Sender: TObject);
var
  test :string;
begin
 lcontr1.Enabled:=False;
 StartTime:=Time;
 reestr:=VarToStr(cbb1.Properties.Grid.DataController.Values
            [cbb1.Properties.Grid.FocusedRowIndex,0]);

 //начальная дата передачи счета в работу
  with cbb1.Properties.Grid.DataController do
    BeginDate := Values[FocusedRecordIndex, 1];

 if reestr<>'' then GetAcCode(StrToInt(reestr));
 lcontr1.Enabled:=True;
end;


procedure TAgentRepForm.btn2Click(Sender: TObject);
begin
  if dlg1.Execute then
 ExportGridToExcel(dlg1.FileName,grd1,false,true,True,'xls');
end;

procedure TAgentRepForm.btn_agrepClick(Sender: TObject);
begin
 //ShowMessage(GetListYm('1005'));
end;

function TAgentRepForm.GetListYm(YM :string) :string;
var
  Q :TFIBQuery;
  s :string;
begin
  Q:=GetQueryForUse(dm1.trnRD,
                          'select distinct(ym) from n_reestrstat order by ym');
  Q.ExecQuery;
   while not Q.Eof do
   begin
    if YM<>Q.FN('ym').AsString then
    begin
      if s<>'' then s:=s+',';
      s:=s+#39+Q.FN('ym').AsString+#39;
      Q.Next;
    end else Break;
     Result:=s;
   end;
  FreeQueryForUse(Q);
end;
{------------------------------------------------------------------------------}
{-------------------------------------------------------------------------------
GetBeforePeriodSumm|Получаем сумму оплат с момента передачи счета до начала
                    отчетного периода
-------------------------------------------------------------------------------}
procedure TAgentRepForm.GetBeforePeriodSumm(s :string);
var
  Q :TFIBQuery;
  sql,srv :string;
begin
  sql:='select acccode,Summa*-1 SumOpl,srv from SchetPrv WHERE Val_Date >= '+
  ' :d1 and Val_Date <:d2'+
  '  and acccode in('+s+
  ') and Prv_Type=1 order by acccode';
  Q:=GetQueryForUse(dm1.trnRD,sql);
  Q.ParamByName('d1').AsDate:=StrToDate(BeginDate);
  Q.ParamByName('d2').AsDate:=
                          GetBeginPeriod(GetYM(cbb2.ItemIndex+1,intedt1.Value));
  Q.ExecQuery;
   while not Q.Eof do
   begin
     if (Kontr.Values[Q.FN('acccode').AsString]='1-1') or
     (Kontr.Values[Q.FN('acccode').AsString]='1-17') then
     srv:=';4000115;4000113;' else
     Srv:=';2548230148;2548137475;';
     if (Pos(';'+Q.FN('Srv').AsString+';', Srv)>0) then
     Sum6.Values[Q.FN('acccode').AsString]:=FloatToStr
     (StrToFloatDef(Sum6.Values[Q.FN('acccode').AsString],0)+
                                                        Q.FN('SumOpl').AsFloat);
     Application.ProcessMessages;
     Q.Next;
   end;
  FreeQueryForUse(Q);

end;
{-------------------------------------------------------------------------------
  GetBeginPeriod|Получаем дату начала периода
-------------------------------------------------------------------------------}
function TAgentRepForm.GetBeginPeriod (ym: string) :TDateTime;
 var
  m,nextm,y,nexty :string;
begin
  m:=Copy(ym,3,2);
  y:=Copy(ym,1,2);
  Result:=StrToDate('01.'+m+'.'+y);
end;
{-------------------------------------------------------------------------------
  GetEndPeriod|Получаем конечную дату периода
-------------------------------------------------------------------------------}
function TAgentRepForm.GetEndPeriod(ym :string) :TDateTime;
 var
  m,nextm,y,nexty :string;
  d3:TDate;
begin
  m:=Copy(ym,3,2);
  y:=Copy(ym,1,2);
  if m='12'then
  begin
    nextm:='01';
    nexty:=IntToStr(StrToInt(y)+1);
  end else
  begin
    nextm:=IntToStr(StrToInt(m)+1);
    nexty:=y;
  end;
  d3:=StrToDate('01.'+nextm+'.'+nexty);
  Result:=d3-1;
end;

end.
